from google.appengine.ext import db
from exceptions import *

class UserData(db.Model):
	firstName = db.StringProperty("")
	lastName = db.StringProperty("")
	address = db.PostalAddressProperty() # DEPRECATO
	iban = db.StringProperty("")
	vatNumber = db.StringProperty("")
	user = db.UserProperty()

	street = db.StringProperty("")
	zipCode = db.StringProperty("")
	city = db.StringProperty("")

	last_renewal = db.DateTimeProperty(auto_now=True)
	user_creation = db.DateTimeProperty(auto_now=True)

	account_customers_count = db.IntegerProperty(default=0)
	account_projects_count = db.IntegerProperty(default=0)

	account_customers_limit = db.IntegerProperty(default=5)
	account_projects_limit = db.IntegerProperty(default=50)
	account_show_banner = db.IntegerProperty(default=1)

	@staticmethod
	def exist(user):
		return bool(UserData.all().filter("user", user).get())

	@staticmethod
	def getRawUserData(user):
		if user:
			userdatadb = UserData.all().filter("user", user).get()
			
			if not userdatadb:
				userdatadb = UserData(user=user)
				userdatadb.put()

			return userdatadb
		else:
			raise NoUserException()

	@staticmethod
	def getUserData(user, **trash):
		userdatadb = UserData.getRawUserData(user)
		return userdatadb.myserialize()

	@staticmethod
	def setUserData(user, firstName=None, lastName=None, address=None, iban=None, vatNumber=None, **trash):
		userdatadb = UserData.getRawUserData(user)

		if firstName:
			userdatadb.firstName = firstName
		if lastName:
			userdatadb.lastName = lastName
		if address:
			if 'street' in address: userdatadb.street = address['street']
			if 'zipCode' in address: userdatadb.zipCode = address['zipCode']
			if 'city' in address: userdatadb.city = address['city']
		if iban:
			userdatadb.iban = iban
		if vatNumber:
			userdatadb.vatNumber = vatNumber

		userdatadb.put()
		return userdatadb.myserialize()
	
	def myserialize(self):
		return {
				'firstName':self.firstName,
				'lastName':self.lastName,
				#'address':self.address,
				'address': {
					'street':self.street,
					'zipCode':self.zipCode,
					'city': self.city
				},
				'iban':self.iban,
				'vatNumber':self.vatNumber,
				'account_customers_count':self.account_customers_count,
				'account_projects_count':self.account_projects_count,
				'account_show_banner':self.account_show_banner,
				'account_customers_limit':self.account_customers_limit,
				'account_projects_limit':self.account_projects_limit,
				'last_renewal':self.last_renewal.isoformat(),
				'user_creation':self.user_creation.isoformat()
			}